package com.jiangxjsy.authorization.property;

import com.jiangxjsy.core.constant.TokenConstant;
import com.jiangxjsy.core.jwt.RsaHelper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * wukong-crm-master
 * 蒋胜宇
 * 2025/5/30 16:49
 */

@Data
@Component
@RefreshScope
@ConfigurationProperties(prefix = "wukong-crm.jwt")
@Slf4j
public class JwtProperty {
    /**
     * RSA密钥种子
     */
    private String secret;

    /**
     * 公钥路径
     */
    private String publicKeyPath;

    /**
     * 私钥路径
     */
    private String privateKeyPath;

    /**
     * 过期时间，单位分钟，默认3天
     */
    private Integer expire = TokenConstant.MAX_JWT_TOKEN_TIME;

    /**
     * 公钥
     */
    private PublicKey publicKey;

    /**
     * 私钥
     */
    private PrivateKey privateKey;

    /**
     * 初始化RSA密钥，Bean 被初始化时执行，初始化失败抛出异常，结束启动
     */
    @PostConstruct
    public void init() {
        try {
            File publicKey = new File(publicKeyPath);
            File privateKey = new File(privateKeyPath);

            if (!publicKey.exists() || !privateKey.exists()) {
                RsaHelper.generateKey(publicKeyPath, privateKeyPath, secret);
                log.debug("RSA key does not exist, RSA keys generated successfully.");
            }

            this.publicKey = RsaHelper.getPublicKey(publicKeyPath);
            this.privateKey = RsaHelper.getPrivateKey(privateKeyPath);
            log.debug("RSA keys load success, public key path: " + publicKeyPath + ", private key path: " + privateKeyPath);
        } catch (Exception e) {
            throw new IllegalStateException("RSA keys load failed, application cannot start.", e);
        }
    }
}
